'''极端简单的模块,输入股票代码,日期(格式为'年-月-日',例如2019-2-13),返回
一个字典,有{'close','open','high','low','vol'},收盘价,开盘价,最高,最低,成交量'''

import sys

import requests
from lxml import etree

## 传入代码,日期字符串,返回当日价格信息.如果获取信息失败,返回None
## 若isDebug = True,在文件夹中记录网页访问的响应文件
def GetStockPrice(code, _date, isDebug = False):
  # 初始化返回字典,以及访问用链接
  result = {}
  symbol = code 
  if symbol.startswith('6'):
    symbol = 'sh'+symbol
  else:
    symbol = 'sz'+symbol
  url = r'http://vip.stock.finance.sina.com.cn/quotes_service/view/vMS_tradehistory.php?symbol=%s&date=%s' % (symbol, _date)
  ## 访问并分析.成功则记录数据,失败返回None
  try:
    resp = requests.get(url)
    if(isDebug):
      with open(sys.path[0]+r'\html_test_result.txt','wb') as f:
        f.write(resp.content)
    tree = etree.HTML(resp.text)
    close_span = tree.xpath('//div[@id="quote_area"]//table//td//span')
    result['close'] = float(close_span[0].text)
    tds = tree.xpath('//div[@id="quote_area"]//table//td')
    result['open'] = float(tds[7].text)
    result['high'] = float(tds[9].text)
    result['low'] = float(tds[11].text)
    result['vol'] = float(tds[13].text)
  except:
    result = None
  return result
  
  
if __name__ == '__main__':
  code = '300059'
  _date = '2019-2-18'
  print(GetStockPrice(code,_date))